import random
import time

from sqlalchemy import and_

from exts import db
from flask import Blueprint, request, Response, jsonify, render_template, url_for, redirect, session
import json

from course.model import Course
from student.model import Student
from user.model import User

course = Blueprint('course', __name__);

# 课程列表
@course.route('course_list', methods=['GET', 'POST'])
def course_list():
    course_list = Course.query.all()
    return render_template('course_list.html', course_list=course_list)

# 删除课程
@course.route('/course/remove', methods=['GET', 'POST'])
def remove():
    id = request.args.get('id')
    course = Course.query.filter(
        Course.id == id
    ).first()
    db.session.delete(course)
    db.session.commit()
    return redirect(url_for('course.course_list'))

# 某时间段课程 详情，编辑，更新，添加
@course.route('/course/edit', methods=['GET', 'POST'])
def edit():
    if request.method=='GET':
        id = request.args.get('id')
        option = request.args.get('option')
        course = Course.query.filter(
            Course.id == id
        ).first()
        if option == 'detail':
            return render_template('course_editor.html', course=course)
        else:
            return render_template('course_editor.html', course=course, update=True)
    else:
        id = request.form.get('id')
        time = request.form.get('time')
        xing1 = request.form.get('xing1')
        xing2 = request.form.get('xing2')
        xing3 = request.form.get('xing3')
        xing4 = request.form.get('xing4')
        xing5 = request.form.get('xing5')
        xing6 = request.form.get('xing6')
        xing7 = request.form.get('xing7')

        course = Course.query.filter(
            Course.id == id
        ).first()
        if course is None:
            course = Course(time=time,xing1=xing1,xing2=xing2,xing3=xing3,xing4=xing4,xing5=xing5,xing6=xing6,xing7=xing7)
            db.session.add(course)
            db.session.commit()
        else:
            course.time = time
            course.xing1 = xing1
            course.xing2 = xing2
            course.xing3 = xing3
            course.xing4 = xing4
            course.xing5 = xing5
            course.xing6 = xing6
            course.xing7 = xing7
            db.session.commit()
        return redirect(url_for("course.course_list"))